{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# _*Pricing Fixed-Income Assets*_ "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "We seek to price a fixed-income asset knowing the distributions describing the relevant interest rates. The cash flows $c_t$ of the asset and the dates at which they occur are known. The total value $V$ of the asset is thus the expectation value of:\n",
    "\n",
    "$$V = \\sum_{t=1}^T \\frac{c_t}{(1+r_t)^t}$$\n",
    "\n",
    "Each cash flow is treated as a zero coupon bond with a corresponding interest rate $r_t$ that depends on its maturity. The user must specify the distribution modeling the uncertainty in each $r_t$ (possibly correlated) as well as the number of qubits he wishes to use to sample each distribution. In this example we expand the value of the asset to first order in the interest rates $r_t$. This corresponds to studying the asset in terms of its duration.\n",
    "<br>\n",
    "<br>\n",
    "The approximation of the objective function follows the following paper:<br>\n",
    "<a href=\"https://arxiv.org/abs/1806.06893\">Quantum Risk Analysis. Woerner, Egger. 2018.</a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:25.388331Z",
     "start_time": "2020-07-13T23:39:23.208125Z"
    }
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "import numpy as np\n",
    "from qiskit import Aer, QuantumCircuit\n",
    "from qiskit.aqua.algorithms import IterativeAmplitudeEstimation\n",
    "from qiskit.circuit.library import NormalDistribution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:26.366384Z",
     "start_time": "2020-07-13T23:39:26.362453Z"
    }
   },
   "outputs": [],
   "source": [
    "backend = Aer.get_backend('statevector_simulator')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Uncertainty Model\n",
    "\n",
    "We construct a circuit factory to load a multivariate normal random distribution in $d$ dimensions into a quantum state.\n",
    "The distribution is truncated to a given box $\\otimes_{i=1}^d [low_i, high_i]$ and discretized using $2^{n_i}$ grid points, where $n_i$ denotes the number of qubits used for dimension $i = 1,\\ldots, d$.\n",
    "The unitary operator corresponding to the circuit factory implements the following: \n",
    "$$\\big|0\\rangle_{n_1}\\ldots\\big|0\\rangle_{n_d} \\mapsto \\big|\\psi\\rangle = \\sum_{i_1=0}^{2^n_-1}\\ldots\\sum_{i_d=0}^{2^n_-1} \\sqrt{p_{i_1,...,i_d}}\\big|i_1\\rangle_{n_1}\\ldots\\big|i_d\\rangle_{n_d},$$\n",
    "where $p_{i_1, ..., i_d}$ denote the probabilities corresponding to the truncated and discretized distribution and where $i_j$ is mapped to the right interval $[low_j, high_j]$ using the affine map:\n",
    "$$ \\{0, \\ldots, 2^{n_{j}}-1\\} \\ni i_j \\mapsto \\frac{high_j - low_j}{2^{n_j} - 1} * i_j + low_j \\in [low_j, high_j].$$\n",
    "\n",
    "In addition to the uncertainty model, we can also apply an affine map, e.g. resulting from a principal component analysis. The interest rates used are then given by:\n",
    "$$ \\vec{r} = A * \\vec{x} + b,$$\n",
    "where $\\vec{x} \\in \\otimes_{i=1}^d [low_i, high_i]$ follows the given random distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:27.609551Z",
     "start_time": "2020-07-13T23:39:27.600449Z"
    }
   },
   "outputs": [],
   "source": [
    "# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.\n",
    "A = np.eye(2)\n",
    "b = np.zeros(2) \n",
    "\n",
    "# specify the number of qubits that are used to represent the different dimenions of the uncertainty model\n",
    "num_qubits = [2, 2]\n",
    "\n",
    "# specify the lower and upper bounds for the different dimension\n",
    "low = [0, 0]\n",
    "high = [0.12, 0.24]\n",
    "mu = [0.12, 0.24]\n",
    "sigma = 0.01*np.eye(2)\n",
    "\n",
    "# construct corresponding distribution\n",
    "bounds = list(zip(low, high))\n",
    "u = NormalDistribution(num_qubits, mu, sigma, bounds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:28.547778Z",
     "start_time": "2020-07-13T23:39:28.126558Z"
    },
    "tags": [
     "nbsphinx-thumbnail"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZEAAAEaCAYAAADQVmpMAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8vihELAAAACXBIWXMAAAsTAAALEwEAmpwYAAApvUlEQVR4nO3debwcVZ338c+XxJvIEoIGB54kkIAZY2YcESPivoCa4IxBBgeC+6AxyqosT1yQxWVGERQGJBNAHMYFEJl5RQ1EFAF5RASBwYkJGiKEC0RAwqKBXGJ+zx9VFyudvn17r6ru7/v16te9feqcqtNFuL/+nVN1ShGBmZlZM7bJuwNmZlZeDiJmZtY0BxEzM2uag4iZmTXNQcTMzJrmIGJmZk3LPYhImiXpx5I2SLpf0mmSxozS5mWSLpK0Om13p6STJY2v0eZASSHplvZ/CjOz/jQ2z4NL2gn4EfBrYB6wJ3AGSXD7VI2mh6R1vwD8Fvg74DPpz3+scpzxwJnA79vYfTOzvpd3JrIQeDZwUERcHRGLgVOBj0maUKPdFyLitRFxfkRcGxFnAycAB0navUr9E4D7gKva/QHMzIpG0px0hGa1pEVVts+UdKOkjZKOr9g2UdLlklZJWinpFbWOlXcQmQssj4jHM2WXkASW143UKCIeqlJ8W/rzedlCSbsBJwLHtNZVM7PiS6cDziX5+zoLmC9pVkW1R4CjgS9V2cVZwFURMRN4MbCy1vHyDiIzgVXZgohYC2xItzXilcBm4M6K8jOAyyLi1mY7aWZWIvsAqyNiTUQMkXwxn5etEBEPRsTNwNPZ8nQE6LXAhWm9oYh4tNbB8g4iOwGPVilfn26ri6RdgE8C/5nNaiS9AXhLus3MrB9MBu7NvB9My+qxB/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Pv0uiHMisSZyLWy14EXBsRT1aUfxs4heSxu/UYTxKMthARG0gfhSxpf+DFwCGSXkwyL/LKtOqNkm6IiDsqdrEx3bdZaTkTsV72d8CtlYURcX1E/L6B/TxC8nCnqiSNJbmk98Q0YL0euCYiVkXEKpJnar+uStOJ6b7NSstBxHqSpGcDe9Ke+YY7gek1ti8E1kfEpZmybTO/bweoon87p3V+04b+meXGQcR61d+Q/PtuRxD5f8Bu6R/+LUjaCTiZ5Pnkw64H9pP0z5L+GXgjcF1F09kkj0f9WRv6Z5Ybz4lYrxqeVL+rDfu6lmTYaQ5b30B4KrA0Ip4ZNouI2ySdyF8m9I+PiMpgNge4LiL+0Ib+meXGz1i3viUpIkKj1wRJZwHPj4i3tuG4Y4B7gEUR8Y1W92eWJw9nWd+RdIGkwfT3QUkX1NHsdOD1kv66DV14B8nd7pe0YV9muXImYlYnSYcCD0RE5fxGo/uZD9wXEde3p2dm+XEQMTOzpnk4y8zMmuYgYmZmTXMQMTOzpjmImJlZ0xxEzMysaQ4iZmbWNAcRMzNrmoOImZk17f8DvPmOhX+BTqsAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plot contour of probability density function\n",
    "x = np.linspace(low[0], high[0], 2**num_qubits[0])\n",
    "y = np.linspace(low[1], high[1], 2**num_qubits[1])\n",
    "z = u.probabilities.reshape(2**num_qubits[0], 2**num_qubits[1])\n",
    "plt.contourf(x, y, z)\n",
    "plt.xticks(x, size=15)\n",
    "plt.yticks(y, size=15)\n",
    "plt.grid()\n",
    "plt.xlabel('$r_1$ (%)', size=15)\n",
    "plt.ylabel('$r_2$ (%)', size=15)\n",
    "plt.colorbar()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Cash flow, payoff function, and exact expected value\n",
    "\n",
    "In the following we define the cash flow per period, the resulting payoff function and evaluate the exact expected value.\n",
    "\n",
    "For the payoff function we first use a first order approximation and then apply the same approximation technique as for the linear part of the payoff function of the [European Call Option](03_european_call_option_pricing.ipynb)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:29.440094Z",
     "start_time": "2020-07-13T23:39:29.189392Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZgAAAEQCAYAAACN2GLgAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8vihELAAAACXBIWXMAAAsTAAALEwEAmpwYAAAjbUlEQVR4nO3de5gcVZ3/8fdHrgEhgcUMyLqGi/wi+cV1dVBBkEFuEncNi0Ai+KxB3Cw+anYx+ANXgYjXIDcXYSVekmUFAoKCECISzATjBjARMRoCBokIIpfdITEJyRLy/f1xakil0jPdPdPVPTP5vJ6nn6aqzqn+dlPMl1PnnDqKCMzMzBrtVa0OwMzMhiYnGDMzK4UTjJmZlcIJxszMSuEEY2Zmpdi+1QEMFHvttVeMGjWq1WEMCWvXrmXXXXdtdRhmPfI12jhLlix5PiJeU+mYE0xm1KhRLF68uNVhDAmdnZ10dHS0OgyzHvkabRxJv+/pmG+RmZlZKZxgzMysFE4wZmZWCicYMzMrRVMTjKRTJP1Q0lOS1khaIukDNdQbLmmmpC5JqyRdJ+kvKpQbL2mppPWSlkmaUM43MTOzaprdgvkksAY4G3gfMB+4XtInqtS7EegAPgJMAg4Bbs0XkHQ4cEt2zhOAOcANko5rWPRmZlazZg9T/ruIeD63/RNJryUlnisrVZB0KHA8cGRE3Jvtewq4X9IxETEvK3o+cG9ETMm250saA1wA/LiE72JmZr1oagumkFy6PQiM7KXaCcAz3cklO88DwOPZMSTtBBwF3FSoOxs4VNLw/sRtZmb1Gwid/IcBy3o5PhpYXmH/w9kxgAOAHSqUe5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TjBm/fNsd3IBiIjfZ0nmbUAAm4AfZGuRdLsH+ICk7SLi5Wzfknxy6cHbgF90J5fs856U9DPg8GzXIdn7D3Nl1ki6G3h77ly/BD4l6WVgXkQ8WuP3NauZ+2DM+qfSolXPAvuQWjfbkW53vZR7zSL9z90+uTrP1PBZ+/RQ7hlgz+yf9wb+HBEvVonz48CtwAXAI5J+K2liDTGY1cwtGLP+GdnDvt8A/0Pq93gnqSVTlP+jX8u6GU8DYyrsb8s+C1J/ym6ShhWSzBZxRsQLwBRgiqQ3Af8PuE7SryJiWQ2xmFXlFoxZ/4yUdFj3hqS/At4CPAD8hNSCGR4Riyu8/rfOz7ofeKuk/XKfty+ps35htuvn2fv7cmVeTRpcUFFE/Ar4FOnvweg6YzLrkVswZv3zPPCfkrpHkV1EapnMioj1kr4BzJZ0MbAY2JnUCjkoIj5S52fNIo0ymyvpAuBlYFoWwzUAEfEbST8E/l3S7qRWz6dII9NeIWkh8APg16TW0z8Ca0mJ0awhnGDM+uf3wJeAr5CGLC8GPpANUQb4GPAo6Q/4RaSRXMuAb9f7QRGxQdIxpCHG3wYEdAIn5YYoA0wC/h24AlgDXEVq2ZycK7MoKzeKlKgeBE7IJneaNYSXTDbrI0mzgP8bEe2tjsVsIHIfjJmZlcIJxszMSuFbZGZmVgq3YMzMrBROMGZmVgonGDMzK4UTjJmZlcIJxszMSvH/AfhURLEx9PCDAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# specify cash flow\n",
    "cf = [1.0, 2.0]\n",
    "periods = range(1, len(cf) + 1)\n",
    "\n",
    "# plot cash flow\n",
    "plt.bar(periods, cf)\n",
    "plt.xticks(periods, size=15)\n",
    "plt.yticks(size=15)\n",
    "plt.grid()\n",
    "plt.xlabel('periods', size=15)\n",
    "plt.ylabel('cashflow ($)', size=15)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:29.698674Z",
     "start_time": "2020-07-13T23:39:29.688947Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exact value:    \t2.1942\n"
     ]
    }
   ],
   "source": [
    "# estimate real value\n",
    "cnt = 0\n",
    "exact_value = 0.0\n",
    "for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):\n",
    "    for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):\n",
    "        prob = u.probabilities[cnt]\n",
    "        for t in range(len(cf)):\n",
    "            # evaluate linear approximation of real value w.r.t. interest rates\n",
    "            exact_value += prob * (cf[t]/pow(1 + b[t], t+1) - (t+1)*cf[t]*np.dot(A[:, t], np.asarray([x1, x2]))/pow(1 + b[t], t+2))\n",
    "        cnt += 1\n",
    "print('Exact value:    \\t%.4f' % exact_value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:30.128058Z",
     "start_time": "2020-07-13T23:39:30.124504Z"
    }
   },
   "outputs": [],
   "source": [
    "# specify approximation factor\n",
    "c_approx = 0.125\n",
    "\n",
    "# get fixed income circuit appfactory\n",
    "from qiskit.finance.applications import FixedIncomeExpectedValue\n",
    "fixed_income = FixedIncomeExpectedValue(num_qubits, A, b, cf, c_approx, bounds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">                                                                           \n",
       "q_0: ───────────────────■──────────────────────────────────────────────────\n",
       "                        │                                                  \n",
       "q_1: ───────────────────┼─────────────■────────────────────────────────────\n",
       "                        │             │                                    \n",
       "q_2: ───────────────────┼─────────────┼─────────────■──────────────────────\n",
       "                        │             │             │                      \n",
       "q_3: ───────────────────┼─────────────┼─────────────┼─────────────■────────\n",
       "     ┌───────────┐┌─────┴──────┐┌─────┴──────┐┌─────┴─────┐┌──────┴───────┐\n",
       "q_4: ┤ RY(9π/16) ├┤ RY(-π/216) ├┤ RY(-π/108) ├┤ RY(-π/27) ├┤ RY(-0.23271) ├\n",
       "     └───────────┘└────────────┘└────────────┘└───────────┘└──────────────┘</pre>"
      ],
      "text/plain": [
       "                                                                           \n",
       "q_0: ───────────────────■──────────────────────────────────────────────────\n",
       "                        │                                                  \n",
       "q_1: ───────────────────┼─────────────■────────────────────────────────────\n",
       "                        │             │                                    \n",
       "q_2: ───────────────────┼─────────────┼─────────────■──────────────────────\n",
       "                        │             │             │                      \n",
       "q_3: ───────────────────┼─────────────┼─────────────┼─────────────■────────\n",
       "     ┌───────────┐┌─────┴──────┐┌─────┴──────┐┌─────┴─────┐┌──────┴───────┐\n",
       "q_4: ┤ RY(9π/16) ├┤ RY(-π/216) ├┤ RY(-π/108) ├┤ RY(-π/27) ├┤ RY(-0.23271) ├\n",
       "     └───────────┘└────────────┘└────────────┘└───────────┘└──────────────┘"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fixed_income.draw()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"word-wrap: normal;white-space: pre;background: #fff0;line-height: 1.1;font-family: &quot;Courier New&quot;,Courier,monospace\">     ┌───────┐┌────┐\n",
       "q_0: ┤0      ├┤0   ├\n",
       "     │       ││    │\n",
       "q_1: ┤1      ├┤1   ├\n",
       "     │  P(X) ││    │\n",
       "q_2: ┤2      ├┤2 F ├\n",
       "     │       ││    │\n",
       "q_3: ┤3      ├┤3   ├\n",
       "     └───────┘│    │\n",
       "q_4: ─────────┤4   ├\n",
       "              └────┘</pre>"
      ],
      "text/plain": [
       "     ┌───────┐┌────┐\n",
       "q_0: ┤0      ├┤0   ├\n",
       "     │       ││    │\n",
       "q_1: ┤1      ├┤1   ├\n",
       "     │  P(X) ││    │\n",
       "q_2: ┤2      ├┤2 F ├\n",
       "     │       ││    │\n",
       "q_3: ┤3      ├┤3   ├\n",
       "     └───────┘│    │\n",
       "q_4: ─────────┤4   ├\n",
       "              └────┘"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "state_preparation = QuantumCircuit(fixed_income.num_qubits)\n",
    "\n",
    "# load probability distribution\n",
    "state_preparation.append(u, range(u.num_qubits))\n",
    "\n",
    "# apply function\n",
    "state_preparation.append(fixed_income, range(fixed_income.num_qubits))\n",
    "\n",
    "state_preparation.draw()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:30.566677Z",
     "start_time": "2020-07-13T23:39:30.561554Z"
    }
   },
   "outputs": [],
   "source": [
    "# set target precision and confidence level\n",
    "epsilon = 0.01\n",
    "alpha = 0.05\n",
    "\n",
    "# set objective qubit\n",
    "objective = u.num_qubits\n",
    "\n",
    "# construct amplitude estimation \n",
    "ae = IterativeAmplitudeEstimation(epsilon=epsilon, alpha=alpha, \n",
    "                                  state_preparation=state_preparation,\n",
    "                                  objective_qubits=[objective],\n",
    "                                  post_processing=fixed_income.post_processing)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:53.292025Z",
     "start_time": "2020-07-13T23:39:30.882045Z"
    }
   },
   "outputs": [],
   "source": [
    "result = ae.run(quantum_instance=Aer.get_backend('qasm_simulator'), shots=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:53.298201Z",
     "start_time": "2020-07-13T23:39:53.294221Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exact value:        \t2.1942\n",
      "Estimated value:    \t2.3404\n",
      "Confidence interval:\t[2.3094, 2.3714]\n"
     ]
    }
   ],
   "source": [
    "conf_int = np.array(result['confidence_interval'])\n",
    "print('Exact value:        \\t%.4f' % exact_value)\n",
    "print('Estimated value:    \\t%.4f' % (result['estimation']))\n",
    "print('Confidence interval:\\t[%.4f, %.4f]' % tuple(conf_int))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-07-13T23:39:53.845834Z",
     "start_time": "2020-07-13T23:39:53.687281Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<h3>Version Information</h3><table><tr><th>Qiskit Software</th><th>Version</th></tr><tr><td>Qiskit</td><td>0.23.3</td></tr><tr><td>Terra</td><td>0.16.2</td></tr><tr><td>Aer</td><td>0.7.3</td></tr><tr><td>Ignis</td><td>0.5.1</td></tr><tr><td>Aqua</td><td>0.8.1</td></tr><tr><td>IBM Q Provider</td><td>0.11.1</td></tr><tr><th>System information</th></tr><tr><td>Python</td><td>3.8.5 (default, Sep  4 2020, 07:30:14) \n",
       "[GCC 7.3.0]</td></tr><tr><td>OS</td><td>Linux</td></tr><tr><td>CPUs</td><td>2</td></tr><tr><td>Memory (Gb)</td><td>3.736370086669922</td></tr><tr><td colspan='2'>Thu Jan 28 13:33:57 2021 IST</td></tr></table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div style='width: 100%; background-color:#d5d9e0;padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'><h3>This code is a part of Qiskit</h3><p>&copy; Copyright IBM 2017, 2021.</p><p>This code is licensed under the Apache License, Version 2.0. You may<br>obtain a copy of this license in the LICENSE.txt file in the root directory<br> of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.<p>Any modifications or derivative works of this code must retain this<br>copyright notice, and modified files need to carry a notice indicating<br>that they have been altered from the originals.</p></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import qiskit.tools.jupyter\n",
    "%qiskit_version_table\n",
    "%qiskit_copyright"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
